package com.cx.auth.model;

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: zhangcx
 * @Description: TODO
 * @date: 2024/1/10 13:16
 * @email: zhangcx@bluemoon.com.cn
 */

public class LocalCache {
    private static final int DEFAULT_CAPACITY = 1024;
    private static final int MAX_CAPACITY = 4096;
    private static final long DEFAULT_TIMEOUT = 2000L;
    private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap(1024);
    private static final Timer TIMER = new Timer();

    LocalCache() {
    }

    public static boolean put(String key, Object object) {
        if (Objects.isNull(object)) {
            return false;
        } else if (checkCapacity()) {
            CACHE.put(key, object);
            TIMER.schedule(new ClearTask(key), 2000L);
            return true;
        } else {
            return false;
        }
    }

    public static boolean put(String key, Object object, long timeOut) {
        if (Objects.isNull(object)) {
            return false;
        } else if (checkCapacity()) {
            CACHE.put(key, object);
            TIMER.schedule(new ClearTask(key), timeOut);
            return true;
        } else {
            return false;
        }
    }

    public static boolean checkCapacity() {
        return CACHE.size() < 4096;
    }

    public static void remove(String key) {
        CACHE.remove(key);
    }

    public static Object get(String key) {
        return CACHE.get(key);
    }

    static class ClearTask extends TimerTask {
        private String key;

        public ClearTask(String key) {
            this.key = key;
        }

        public void run() {
            LocalCache.remove(this.key);
        }
    }
}
